﻿using EFFC.Frame.Net.Module.Extend.EWRA.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using EFFC.Extends.LinqDLR2SQL;
using EFFC.Frame.Net.Unit.DB;
using System.IO;
using EFFC.Frame.Net.Base.Common;
using EFFC.Frame.Net.Base.Data.Base;
using ICPFrameLib.Business;
using ICPFrameLib.Attributes;
using EFFC.Frame.Net.Unit.DB.Parameters;
using EFFC.Frame.Net.Module.Extend.EWRA.Attributes.Validation;
using ICPFrameLib.Common;

namespace XHRPMIS.Business.v1._0
{

   public class ICPSystem : MyRestLogic
{
    private string Setup_Json_File_Path
    {
        get
        {
            return ComFunc.nvl(MyConfig.GetConfiguration("Setup", "Setup_Json_File_Path"));
        }
    }
    private string InitData_Json_File_Path
    {
        get
        {
            return ComFunc.nvl(MyConfig.GetConfiguration("Setup", "InitData_Json_File_Path"));
        }
    }
    private string SystemSecretKey
    {
        get
        {
            return ComFunc.nvl(MyConfig.GetConfiguration("EFFC", "SystemSecretKey"));
        }
    }
    /// <summary>
    /// 是否运行执行系统安装
    /// </summary>
    public bool IsEnableSetup
    {
        get
        {
            return BoolStd.IsNotBoolThen(MyConfig.GetConfiguration("Setup", "IsEnable"), false);
        }
    }
    [EWRAVisible(false)]
    [EWRAAuth(false)]
    [EWRARunMode("Dev,Update")]
    [EWRARoute("post", "/system/onekeyinstall")]
    [EWRARouteDesc("系统一键安装")]
    [EWRAOutputDesc("返回结果", @"{
code:""success-成功，failed-失败"",
msg:""提示信息""
}")]
    public object OneKeyInstall()
    {
        var secretkey = ComFunc.nvl(HeaderData["SystemSecretKey"]);
        if (secretkey == "") secretkey = ComFunc.nvl(HeaderData["systemsecretkey"]);
        if (secretkey == "") secretkey = ComFunc.nvl(HeaderData["Systemsecretkey"]);
        if (secretkey != SystemSecretKey)
        {
            return new
            {
                code = "failed",
                msg = "系统运维密钥不正确"
            };
        }

        if (!IsValidBy((msg) =>
        {
            if (!IsEnableSetup)
            {
                msg.Append("不可访问");
                return false;
            }
            else
            {
                return true;
            }
        }))
        {
            return null;
        }
        BeginTrans();
        var up = DB.NewMetaUnitParameter();
        var result = FrameDLRObject.CreateInstance(DoSetup(up), EFFC.Frame.Net.Base.Constants.FrameDLRFlags.SensitiveCase);
        if (result.Code == "failed")
        {
            return result;
        }
        var rtn = DoInitData(up);
        CommitTrans();
        return rtn;
    }
    [EWRAVisible(false)]
    [EWRAAuth(false)]
    [EWRARunMode("Dev,Update")]
    [EWRARoute("post", "/system/setup")]
    [EWRARouteDesc("系统初始化安装")]
    [EWRAOutputDesc("返回结果", @"{
code:""success-成功，failed-失败"",
msg:""提示信息""
}")]
    public object Setup()
    {
        var secretkey = ComFunc.nvl(HeaderData["SystemSecretKey"]);
        if (secretkey == "") secretkey = ComFunc.nvl(HeaderData["systemsecretkey"]);
        if (secretkey == "") secretkey = ComFunc.nvl(HeaderData["Systemsecretkey"]);
        if (secretkey != SystemSecretKey)
        {
            return new
            {
                code = "failed",
                msg = "系统运维密钥不正确"
            };
        }

        if (!IsValidBy((msg) =>
        {
            if (!IsEnableSetup)
            {
                msg.Append("不可访问");
                return false;
            }
            else
            {
                return true;
            }
        }))
        {
            return null;
        }
        BeginTrans();
        var up = DB.NewMetaUnitParameter();
        var rtn = DoSetup(up);
        return new
        {
            code = "success",
            msg = "创建成功"
        };
    }
    [EWRAVisible(false)]
    [EWRAAuth(false)]
    [EWRARunMode("Dev,Update")]
    [EWRARoute("post", "/system/init")]
    [EWRARouteDesc("系统初始化数据")]
    [EWRAOutputDesc("返回结果", @"{
code:""success-成功，failed-失败"",
msg:""提示信息""
}")]
    public object InitData()
    {
        var secretkey = ComFunc.nvl(HeaderData["SystemSecretKey"]);
        if (secretkey == "") secretkey = ComFunc.nvl(HeaderData["systemsecretkey"]);
        if (secretkey == "") secretkey = ComFunc.nvl(HeaderData["Systemsecretkey"]);
        if (secretkey != SystemSecretKey)
        {
            return new
            {
                code = "failed",
                msg = "系统运维密钥不正确"
            };
        }

        if (!IsValidBy((msg) =>
        {
            if (!IsEnableSetup)
            {
                msg.Append("不可访问");
                return false;
            }
            else
            {
                return true;
            }
        }))
        {
            return null;
        }
        var up = DB.NewMetaUnitParameter();
        BeginTrans();
        var rtn = DoInitData(up);
        CommitTrans();
        return rtn;
    }
    [EWRAVisible(false)]
    [EWRAAuth(false)]
    [EWRARunMode("Dev,Update")]
    [EWRARoute("get", "/system/getconfigs")]
    [EWRARouteDesc("获取系统中所有的配置参数")]
    [EWRAOutputDesc("返回结果", @"{
code:""success-成功，failed-失败"",
msg:""提示信息""
data:'配置档中的所有内容'
}")]
    public object GetConfigs()
    {
        SetCacheEnable(false);
        var secretkey = ComFunc.nvl(HeaderData["SystemSecretKey"]);
        if (secretkey == "") secretkey = ComFunc.nvl(HeaderData["systemsecretkey"]);
        if (secretkey == "") secretkey = ComFunc.nvl(HeaderData["Systemsecretkey"]);
        if (secretkey != SystemSecretKey)
        {
            return new
            {
                code = "failed",
                msg = "系统运维密钥不正确"
            };
        }

        if (!IsValidBy((msg) =>
        {
            if (!IsEnableSetup)
            {
                msg.Append("不可访问");
                return false;
            }
            else
            {
                return true;
            }
        }))
        {
            return null;
        }

        return new
        {
            code = "success",
            msg = "",
            data = File.ReadAllText(MyConfig.ConfigFilePath)
        };
    }
    [EWRAVisible(false)]
    [EWRAAuth(false)]
    [EWRARunMode("Dev,Update")]
    [EWRAEmptyValid("data")]
    [EWRARoute("patch", "/system/updateconfigs")]
    [EWRAAddInput("data", "string", "配置档内容", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, false)]
    [EWRARouteDesc("修改系统的配置档")]
    [EWRAOutputDesc("返回结果", @"{
code:""success-成功，failed-失败"",
msg:""提示信息""
}")]
    public object UpdateConfigs()
    {
        SetCacheEnable(false);
        var secretkey = ComFunc.nvl(HeaderData["SystemSecretKey"]);
        if (secretkey == "") secretkey = ComFunc.nvl(HeaderData["systemsecretkey"]);
        if (secretkey == "") secretkey = ComFunc.nvl(HeaderData["Systemsecretkey"]);
        if (secretkey != SystemSecretKey)
        {
            return new
            {
                code = "failed",
                msg = "系统运维密钥不正确"
            };
        }

        if (!IsValidBy((msg) =>
        {
            if (!IsEnableSetup)
            {
                msg.Append("不可访问");
                return false;
            }
            else
            {
                return true;
            }
        }))
        {
            return null;
        }
        var content = ComFunc.nvl(PostDataD.data);
        if (!FrameDLRObject.IsJson(content))
        {
            return new
            {
                code = "failed",
                msg = "文档内容格式不正确"
            };
        }
        MyConfig.Configuration.WriteConfigs(content);
        return new
        {
            code = "success",
            msg = "操作成功"
        };
    }
    [EWRAVisible(true)]
    [EWRAAuth(true)]
    [EWRARoute("get", "/system/fileservice/token")]
    [EWRARouteDesc("获取文件服务器的访问token")]
    [EWRAOutputDesc("返回结果", @"{
code:""success-成功，failed-失败"",
msg:""提示信息"",
data:'token值'
}")]
    public object GetFileServiceToken()
    {
        SetCacheEnable(false);
        var msg = "";
        var token = "";
        if (!new RemoteFileAccess().GetAccessToken(ref msg, ref token))
        {
            return new
            {
                code = "failed",
                msg
            };
        }
        else
        {
            return new
            {
                code = "success",
                msg = "",
                data = token
            };
        }
    }

    private object DoInitData(UnitParameter up)
    {
        if (!Directory.Exists(InitData_Json_File_Path))
        {
            return new
            {
                code = "failed",
                msg = "初始化数据脚本目录不存在，无法创建"
            };
        }
        foreach (var f in Directory.GetFiles(InitData_Json_File_Path, "*.json", SearchOption.AllDirectories))
        {
            var content = File.ReadAllText(f).Trim();
            using (var dobj = FrameDLRObject.IsJsonThen(content, (FrameDLRObject)FrameDLRObject.CreateInstance(), EFFC.Frame.Net.Base.Constants.FrameDLRFlags.SensitiveCase))
            {
                var tablename = ComFunc.nvl(dobj.GetValue("table"));
                var data = (IEnumerable<object>)dobj.GetValue("data");
                var pk = (IEnumerable<object>)dobj.GetValue("pk");
                foreach (FrameDLRObject item in data)
                {
                    FrameDLRObject w = FrameDLRObject.CreateInstance();
                    foreach (string s in pk)
                    {
                        w.SetValue(s, item.GetValue(s));
                    }
                    DB.QuickDelete(up, tablename, w);
                    DB.QuickInsert(up, tablename, item);
                }
            }
        }
        return new
        {
            code = "success",
            msg = "创建成功"
        };
    }

    private object DoSetup(UnitParameter up)
    {
        if (!Directory.Exists(Setup_Json_File_Path))
        {
            return new
            {
                code = "failed",
                msg = "创建脚本目录不存在，无法创建"
            };
        }
        foreach (var f in Directory.GetFiles(Setup_Json_File_Path, "*.json", SearchOption.AllDirectories))
        {
            var content = File.ReadAllText(f).Trim();
            using (var dobj = FrameDLRObject.IsJsonThen(content, (FrameDLRObject)FrameDLRObject.CreateInstance(), EFFC.Frame.Net.Base.Constants.FrameDLRFlags.SensitiveCase))
            {
                var tablename = ComFunc.nvl(dobj.GetValue("$table"));
                if (!DB.IsTableExists(up, tablename))
                {
                    DB.Excute(up, content);
                }
            }
        }
        return new
        {
            code = "success",
            msg = "创建成功"
        };
    }
}
}
